import { Component, OnInit } from '@angular/core';
import {DomSanitizer, SafeUrl} from '@angular/platform-browser';
import { HttpService } from '../http.service';
import {ActivatedRoute} from '@angular/router';
import { Router } from '@angular/router';
import * as ons from 'onsenui';

@Component({
  selector: 'app-bind-id',
  templateUrl: './bind-id.component.html',
  styleUrls: ['./bind-id.component.less']
})
export class BindIdComponent implements OnInit {
  id;
  isEdit:boolean = false;
  srcA:SafeUrl;
  srcB:SafeUrl;
  fileA;
  fileB;
  uploading: boolean = false;


  getSrc(src): SafeUrl{
    return this.sanitizer.bypassSecurityTrustUrl(src);
  }

  addA(e):void{
    this.fileA = e.target.files[0];
    const src = window.URL.createObjectURL(this.fileA);
    const safeSrc = this.getSrc(src);
    this.srcA = safeSrc;
  }
  addB(e):void{
    this.fileB = e.target.files[0];
    const src = window.URL.createObjectURL(this.fileB);
    const safeSrc = this.getSrc(src);
    this.srcB = safeSrc;
  }

  constructor(private router: Router, private route: ActivatedRoute, private http: HttpService, private sanitizer:DomSanitizer) {
    this.id = this.route.snapshot.params['id'];
    this.isEdit = this.route.snapshot.queryParams['isEdit'];
    if(this.isEdit) document.title = '编辑';
   }

  async upload() {
    if(this.uploading) return;
    this.uploading = true;
    const fmA = new FormData();
    fmA.append('name', 'car.upload.img');
    fmA.append('img', this.fileA);
    const fmB = new FormData();
    fmB.append('name', 'car.upload.img');
    fmB.append('img', this.fileB);
    try {
      const res = await Promise.all([this.http.form(fmA),this.http.form(fmB)])
      const {success, msg} = await this.http.post({
        name: 'car.sys.bind.driving.license',
        car_id: this.id,
        driving_license: res[0].data.original+','+res[1].data.original
      });

      if(success) history.back();
      else {
        this.uploading = false;
        ons.notification.toast(msg, {timeout: 2000});
      }
    } catch(e) {
      alert('服务器出故障了!');
      this.uploading = false;
    }
  }

  ngOnInit(){

  }

}
